const puppeteer = require("puppeteer");
const redis = require("../config/redis");
const { logger } = require("../config/utils");
const { redisKey, bMapKey } = require("../config/env");
const mongoose = require("mongoose");
// 休息
const sleep = delay => new Promise(resolve => setTimeout(() => resolve(), delay));

// 更新详情 area c6 城六区  ca 长安
const updateDateil = async (area) => {
	const key = redisKey.houseLinkInfo +  "_" + area;
	const House = mongoose.model("House");
	const houseLinkString = await redis.get(key);
	const houseLinkObj = JSON.parse(houseLinkString);
	let links = [];
	Object.keys(houseLinkObj).forEach(key => {
		if(houseLinkObj[key] === "notUpdate") {
			links.push(key);
		}
	});
	puppeteer.launch({ headless: true, args: ["--no-sandbox", "--disable-setuid-sandbox"]}).then(async browser => {
		console.log("****** 打开浏览器 ******");
		const page = await browser.newPage();
		for (let i = 0; i < links.length; i++) {
			// 获取详情 ----------------------------------------------------------------------
			const delay = parseInt(Math.random() * 2000 + 2000);
			console.log(`****** 延迟${delay / 1000} 秒  总共 ${links.length} 条 获取第 ${i + 1} 条 ******`);
			console.log("[link] :" + links[i]);
			await page.goto(links[i], { waitUntil: "networkidle0" });
			try {
				await page.waitForSelector("body .tc");
			} catch (error) {
				console.log("等待三秒 再试一次！");
				await sleep(3000);
				await page.goto(links[i], { waitUntil: "networkidle0" });
				await page.waitForSelector("body .tc");
			}
			await sleep(delay);
			let modalDatas = await page.evaluate(() => {
				// 标题
				const title = $(".tc font").text();
				// 开发商
				const kfs = $($("table td span")[0]).text();
				// 咨询电话
				const phone = $($("table td span")[1]).text();
				// 房子栋数
				const houseNumber = $($("table td span")[2]).text();
				// 预（现）售证号
				const sId = $($("table td span")[4]).text();
				// 意向登记时间
				const yxdjTimeStart = $($("table td")[9]).text().split(" 至 ")[0];
				const yxdjTimeEnd = $($("table td")[9]).text().split(" 至 ")[1];
				// 接受资料时间
				const receiveTimeStart = $($("table td")[11]).text().split(" 至 ")[0];
				const receiveTimeEnd = $($("table td")[11]).text().split(" 至 ")[1];
				// 现场接受资料地点
				const address = $($("table td")[13]).text();
				// 内容
				const content = $("#ltrXsgg").html();
				// 价钱
				let prices = [];
				let PriceReg = /([\d]+.[\d]+|[\d]+)元/g;
				while (PriceReg.test($("#ltrXsgg").text())) {
					prices.push(RegExp.$1);
				}
				return `${title}-----${kfs}-----${phone}-----${houseNumber}-----${sId}-----${yxdjTimeStart}-----${yxdjTimeEnd}-----${receiveTimeStart}-----${receiveTimeEnd}-----${address}-----${content}-----${prices.join("&")}`;
			});
			modalDatas = modalDatas.replace(",", "，");
			modalDatas = modalDatas.split("-----");
			let house = await House.findOne({link: links[i]});
			house.title = modalDatas[0];
			house.kfs = modalDatas[1];
			house.phone = modalDatas[2];
			house.houseNumber = modalDatas[3];
			house.sId = modalDatas[4];
			house.yxdjTimeStart = modalDatas[5];
			house.yxdjTimeEnd = modalDatas[6];
			house.receiveTimeStart = modalDatas[7];
			house.receiveTimeEnd = modalDatas[8];
			house.address = modalDatas[9];
			house.content = modalDatas[10];
			house.prices = modalDatas[11].split("&");
			house.area = area;
			const url = `https://restapi.amap.com/v3/geocode/geo?city=西安市&output=json&key=${bMapKey}`;
			// 获取经纬度信息
			await page.goto(url + "&address=" + house.address, { waitUntil: "networkidle0" });
			await page.waitForSelector("body pre");
			const lngLatString = await page.evaluate(() => {
				const dom = document.getElementsByTagName("pre");
				return dom[0].innerText;
			});
      
			let lngLatJson = JSON.parse(lngLatString);
			if(lngLatJson.status === "1") {
				const location = lngLatJson.geocodes[0].location.split(",");
				house.lng = parseFloat(location[0]);
				house.lat = parseFloat(location[1]);
			}
			console.log(`经纬度信息：${house.lng} ${house.lat}`);
			try {
				const result = await house.save();
				if(result.link) {
					logger("task_house_detail", `${result.title}---${result.link}---${house.lng}---${house.lat}`);
					console.log(`****** 保存 [${result.link}] 数据成功！ ******`);
					try {
						const houseLinks = await redis.get(key);
						const houseLinksObj = JSON.parse(houseLinks);
						houseLinksObj[result.link] = "updated";
						await redis.set(key, JSON.stringify(houseLinksObj));
						console.log(`****** 更新redis [${result.link}] 数据成功！ ******`);
					} catch (error) {
						console.log(`****** 更新redis [${result.link}] 数据失败! ****** \n ${error.stack}`);
						logger("task_house_detail_error", error.stack);
					}
				}
			} catch (error) {
				logger("task_house_detail_error", error.stack);
				console.log(`****** 更新redis [${house.link}] 数据失败! ****** \n ${error.stack}`);
				logger("task_house_detail_error", error.stack);
			}
		}
		console.log(`****** 保存 ${links.length}条 数据成功！ ******`);
		await browser.close();
	}).catch((error) => {
		console.log(error.stack);
	});
};

module.exports = updateDateil;